import java.util.Arrays;

/**
 * @author tmh
 * @date 2024/10/14 20:54
 * @description
 */
public class T16最接近的三数之和 {

    /**
     * 思路类似于三数之和
     *
     * @param nums
     * @param target
     * @return
     */
    public int threeSumClosest(int[] nums, int target) {
        //数组排序
        Arrays.sort(nums);
        int closestSum = nums[0]+nums[1]+nums[2];
        //这里i的结束范围是需要进行-2的，不然下面的nums[left]和nums[right]会越界
        for (int i = 0; i < nums.length - 2; i++) {
            int num1 = nums[i];
            int left = i + 1;
            int right = nums.length - 1;

            while (left < right) {
                int num2 = nums[left];
                int num3 = nums[right];
                int sum = num1 + num2 + num3;
                if (Math.abs(sum - target) < Math.abs(closestSum - target)) {
                    closestSum = sum;
                }
                if (sum < target) {
                    left++;
                } else if (sum > target) {
                    right--;
                } else {
                    //如果相等
                    return sum;
                }
            }
        }
        return closestSum;
    }
}
